import { ElMessage } from 'element-plus'
import { reactive } from 'vue'
import { login } from '@/network/api/home'
// 登录
const useLoginEffect = (loginFromRef, router) => {
  const loginFrom = reactive({ username: '', password: '' })
  const clickLoginBtn = () => {
    loginFromRef.value.validate(valid => {
      if (valid) {
        // 发送请求 请求成功后跳转
        login(loginFrom).then(res => {
          console.log(res)
          if (res.status == 200) {
            sessionStorage.setItem('token', res.result.token)
            ElMessage.success('login success')
            router.push('/home')
          }

        })
      } else {
        return false
      }
    })
  }
  return {
    loginFrom,
    clickLoginBtn
  }
}

// 校验 重置
const useLoginValidate = (loginFromRef) => {
  const rules = reactive({
    username: [{ required: true, message: 'please input username', trigger: 'blur' }],
    password: [{ required: true, message: 'please input password', trigger: 'blur' }]
  })
  const resetForm = () => {
    loginFromRef.value.resetFields()
  }
  return {
    rules,
    resetForm
  }
}


export {
  useLoginEffect,
  useLoginValidate
}